package com.fenghongzhang.module_main.ui.search

import androidx.lifecycle.viewModelScope
import com.fenghongzhang.lib_core.base.BaseViewModel
import com.fenghongzhang.lib_core.utils.GSON
import com.jczy.cyclone.mmkv.AppMMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SearchViewModel @Inject constructor(private val mRepository: SearchRepository) : BaseViewModel() {
    //历史数据
    val mSearchHistoryData = MutableStateFlow<List<String>>(listOf())

    companion object {
        private const val DEFAULT_SEARCH_HISTORY_NUM = 10
    }

    //搜索关键词
    val mKeywords = MutableStateFlow("")
    //获取历史数据
    fun getSearchHistory() {
        viewModelScope.launch(Dispatchers.IO) {
            if (AppMMKV.searchHistory.isNotEmpty()) {
                val historyList = GSON.fromJson<List<String>>(AppMMKV.searchHistory) ?: listOf()
                //倒序
                mSearchHistoryData.emit(historyList.reversed())
            }
        }
    }
    fun clearKeyword() {
        mKeywords.value = ""
    }

    //添加历史数据
    fun addSearchHistory(content: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val historyList = GSON.fromJson<MutableList<String>>(AppMMKV.searchHistory) ?: mutableListOf()
            val isContains = historyList.contains(content)
            //不操作
            if (isContains && historyList.indexOf(content) == historyList.lastIndex) {
                return@launch
            }
            //移除记录
            if (historyList.size >= DEFAULT_SEARCH_HISTORY_NUM) {
                if (!isContains)
                    historyList.removeAt(0)
                else
                    historyList.removeAt(historyList.indexOf(content))
            } else {
                if (isContains)
                    historyList.removeAt(historyList.indexOf(content))
            }
            //添加记录
            historyList.add(content)
            //保存
            AppMMKV.searchHistory = GSON.toJson(historyList)
            //通知更新
            mSearchHistoryData.emit(historyList.reversed())
        }
    }
}